import { _decorator, Component, instantiate, Layout, Prefab, Sprite } from 'cc'
import { PlayerController } from '../actor/PlayerController'
const { ccclass, property } = _decorator

@ccclass('UIHPBar')
export class UIHPBar extends Component {
    @property(Prefab)
    heartPrefab: Prefab | null = null;
    layout: Layout = null;
    start() {
        this.layout = this.node.getComponent(Layout)
    }

    update(deltaTime: number) {

        if (!PlayerController.instance || !PlayerController.instance.actor) {
            return
        }
        const HEART_RATIO = 10
        let hp = PlayerController.instance.actor.hp
        let maxHp = PlayerController.instance.actor.maxHp
        // 每个心代表10血 计算有最多有多少颗心
        let div = maxHp / HEART_RATIO
        const maxHeart = Math.ceil(div)
        // 余数
        const percent = hp % HEART_RATIO / HEART_RATIO
        // 当前满心数
        let flr = Math.floor(hp / HEART_RATIO)
        let curr = this.layout.node.children.length
        while (curr < maxHeart) {
            let newHeart = instantiate(this.heartPrefab)
            this.layout.node.addChild(newHeart)
            curr++

        }

        let children = this.node.children
        // 显示百分比
        for (let i = 0; i < children.length; i++) {
            let childRenderer = children[i].getChildByName("HP").getComponent(Sprite)
            if (i < flr)
                childRenderer.fillRange = 1
            else if (i == flr)
                childRenderer.fillRange = percent
            else
                childRenderer.fillRange = 0
        }
        this.layout.updateLayout()

    }
}

